﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Proggy.Web.Cms.PropertyTypes;
using Proggy.Web.Cms.Core.AutoRenderModels;
using System.Net.NetworkInformation;
using QDFeedParser;
using System.Net;
using Newtonsoft.Json;

namespace Proggy.Web.Cms.Core.PropertyTypes
{
    /// <summary>
    /// Rss property type
    /// </summary>
    [PropertyType("Rss feed", "~/Areas/ProggyCore/Views/EditorPartials/RssFeedEditor.cshtml")]
    public class RssReader : PropertyTypeBase, IValidatablePropertyType, IAutoRenderPropertyType
    {
        public string Name { get; set; }
        public string FeedUrl { get; set; }
        public int Count { get; set; }
        public string MoreUrl { get; set; }

        public Tuple<bool, string> GetIsValid(System.ComponentModel.DataAnnotations.ValidationContext vContext, ContentModel.ContentModelPropertyTypeAttribute attr)
        {
            if (Count < 1 || string.IsNullOrEmpty(FeedUrl)) {
                return new Tuple<bool, string>(false, "Number to display must be more than 0 and Url cannot be empty!");
            }

            // ping url
            var fac = new HttpFeedFactory();
            try
            {
                if (!fac.PingFeed(new Uri(FeedUrl)))
                {
                    return new Tuple<bool, string>(false, FeedUrl + " did not receive a reply");
                }
            }
            catch {
                return new Tuple<bool, string>(false, FeedUrl + " did not receive a reply");
            }

            // ping more
            if (!string.IsNullOrWhiteSpace(MoreUrl))
            {

                try
                {
                    // 
                    var req = HttpWebRequest.Create(MoreUrl);
                    var resp = (HttpWebResponse)req.GetResponse();
                    if (resp.StatusCode != HttpStatusCode.OK){
                        return new Tuple<bool, string>(false, MoreUrl + " did not receive a reply - check this url is valid");
                    }
                }
                catch
                {
                    return new Tuple<bool, string>(false, MoreUrl + " did not receive a reply - check this url is valid");
                }
            }            

            // all is well
            return new Tuple<bool, string>(true, "");
        }

        public object GetAutoRenderModel()
        {
            return new RssReaderAutoRenderModel(this);
        }

        [JsonIgnore]
        public string FullPathToAutoRenderPartial
        {
            get {
                return "~/Areas/ProggyCore/Views/AutoRenderPartials/_RssReader.cshtml";
            }
        }
    }
}
